(function() {
	var startBtn, endBtn, startTime, endTime,nurseid;
	var category;
	var categoryData = [];
	mui.init({
		swipeBack: true //启用右滑关闭功能
	});
	mui.plusReady(function() {
		var title = document.getElementById("mui-title");
		var texttip = document.getElementById("text");
		var perInfo = app.getState()
		if (perInfo) {
			nurseid = perInfo.loginID
		}
		//if(groupCode == 'nurhead' || groupCode == 'znurhead') {
			title.innerText = '本科室压疮统计';
			texttip.innerText = '当前护士长角色可查询本科室压疮数据'
		// } else if(groupCode == 'nurse') {
		// 	mui.toast('护士角色无权限');
		// 	title.innerText = '压疮人数统计查询';
		// 	texttip.innerText = '当前护士角色无权查询！'
		// 	return;
		// }
		startBtn = document.getElementById("starttime");
		endBtn = document.getElementById("endtime");
		var timeArr = getStartAndEndTime();
		startTime = timeArr[0];
		startBtn.innerText = startTime;
		endTime = timeArr[1];
		endBtn.innerText = endTime;

		startBtn.addEventListener('tap', function() {
			selectDate(this);
		});
		endBtn.addEventListener('tap', function() {
			selectDate(this);
		});

		var fixHead = document.getElementById('fixHead');
		var ExcelHead = document.getElementById('ExcelHead');
		var scroll = document.getElementById('scroll');

		//设置年/半年/季度/月份 选择
		selectionSetting();
		category = "";
		for(var i = 0; i < 4; i++) {
			var checkObj = document.getElementById("check" + (i + 1));
			if(checkObj.checked) {
				category = checkObj.value;
				// console.log(category.length);
				break;
			}
		}
		if(category.length > 0) {
			requestYCData();
		}
	});

	/*
	 * 请求压疮数据
	 */
	function requestYCData() {
		plus.nativeUI.showWaiting('正在查询');
		var pdict = {'parr':startTime + '^' + endTime,nurseid:nurseid}
		var paramDict = {'method':'web.INMOutInterface:FindYCList','params':JSON.stringify(pdict),'type':'RecQuery'}
		// console.log(JSON.stringify(pdict))
		mui.DHCWebService(paramDict, function(result) {
			plus.nativeUI.closeWaiting();
			if (result.msgcode != '1') {
				mui.toast(result.msg)
				return;
			}
		// 	console.log(JSON.stringify(result.data));
			prepareYCData(result.data);
			plus.nativeUI.closeWaiting();
		}, function(error) {
			mui.toast(error);
			categoryData.splice(0, categoryData.length);
			//清空界面
			var ycTbody = document.getElementById('ycTbody');
			ycTbody.innerHTML = ''
			plus.nativeUI.closeWaiting();
		});
	}

	/*
	 * 重新组合数据
	 * {'LocDesc': '重症医学科外科一病房','Year': '[2018]','Count': '[{8,4,1,3,7,5,4,4,6,10,4,5}]'}
	 * {warddesc: '普通外科',total: '88',years: [{year: '2016',partTotal: '40',elements: ['8', '9', '10', '11','8', '9', '10', '11','8', '9', '10', '11']},{year: '2017',partTotal: '44',elements: ['9', '10', '11', '12','9', '10', '11', '12','9', '10', '11', '12']}]}
	 * 
	 */
	function prepareYCData(oldArray) {
		if(oldArray.length == 0) {
			mui.toast('该时间段无压疮数据');
			//清空界面
			var ycTbody = document.getElementById('ycTbody');
			ycTbody.innerHTML = ''
			categoryData.splice(0, categoryData.length);
			return;
		}
		var resultArray = [];
		var fullYearArray = getYearArray(startTime, endTime);
		var yearIntArr = [];
		for(var i = 0; i < oldArray.length; i++) {
			var oneData = oldArray[i];
			var oneResult = {};
			oneResult['warddesc'] = oneData['LocDesc'];
			var yearArr = eval(oneData['Year']);
			var CountArr = eval(oneData['Count']);
			var years = [];
			var total = 0;
			for(var j = 0; j < fullYearArray.length; j++) {
				var oneYearInt = fullYearArray[j];
				var yearIndex = yearArr.indexOf(oneYearInt);
				var oneYear = {};
				if(yearIndex == -1) {
					oneYear['partTotal'] = "";
					oneYear['year'] = oneYearInt;
					var elements = [];
					for(var k = 0; k < 12; k++) {
						elements[k] = "";
					}
					oneYear['elements'] = elements;
				} else {
					var oneYearData = yearArr[yearIndex];
					var oneCountData = CountArr[yearIndex];

					oneYear['year'] = oneYearData;
					var partTotal = 0;
					var elements = [];
					for(var k = 0; k < 12; k++) {
						if(oneCountData.length < 12) {
							oneCountData[11] = "";
						}
						var oneCountStr = oneCountData[k];
						if(oneCountStr == null) {
							elements[k] = "";
						} else if((typeof oneCountStr) == 'string' && oneCountStr.length == 0) {
							elements[k] = "";
						} else {
							elements[k] = oneCountStr + '';
							var oneCount = parseInt(oneCountStr);
							partTotal += oneCount;
						}
					}
					oneYear['partTotal'] = partTotal;
					oneYear['elements'] = elements;
					total += partTotal;
				}
				years[j] = oneYear;
				//console.log('oneYear[year]',oneYear['year'])
			}
			oneResult['years'] = years;
			oneResult['total'] = total;
			resultArray[i] = oneResult;
		}
		categoryData = resultArray;
		updateHeader();
	}

	/*
	 * 更新头部
	 */
	function updateHeader() {
		var resultArray = [];
		if(category != "按月") {
			//根据category 进行组合数据
			for(var i = 0; i < categoryData.length; i++) {
				var oneData = categoryData[i];
				var oneResult = {};
				oneResult['warddesc'] = oneData['warddesc'];
				oneResult['total'] = oneData['total'];
				var yearsArr = oneData['years']
				var categoryArr = [];
				for(var j = 0; j < yearsArr.length; j++) {
					var oneYearsData = yearsArr[j];
					var onecategoryData = {};
					onecategoryData['year'] = oneYearsData['year'];
					onecategoryData['partTotal'] = oneYearsData['partTotal'];
					if(category == "按年查询") {
						onecategoryData['elements'] = [];
					} else if(category == "按半年") {
						var newElements = [0, 0];
						var oneElements = oneYearsData['elements'];
						for(var k = 0; k < oneElements.length; k++) {
							if(oneElements[k] != null && oneElements[k].length > 0) {
								var elementInt = parseInt(oneElements[k]);
								if(k < 6) {
									newElements[0] += elementInt;
								} else {
									newElements[1] += elementInt;
								}
							}
						}
						if(newElements[0] == 0) {
							newElements[0] = "";

						}
						if(newElements[1] == 0) {
							newElements[1] = "";
						}
						onecategoryData['elements'] = newElements;
					} else if(category == "按季度") {
						var newElements = [0, 0, 0, 0];
						var oneElements = oneYearsData['elements'];
						for(var k = 0; k < 12; k++) {
							if(oneElements[k] != null && oneElements[k].length > 0) {
								var elementInt = parseInt(oneElements[k]);
								if(k < 3) {
									newElements[0] += elementInt;
								} else if(k < 6 && k > 2) {
									newElements[1] += elementInt;
								} else if(k < 9 && k > 5) {
									newElements[2] += elementInt;
								} else {
									newElements[3] += elementInt;
								}
							}
						}
						for(var k = 0; k < newElements.length; k++) {
							//console.log('newElements[k]',newElements[k])
							if(newElements[k] == 0) {
								newElements[k] = "";
							}
						}
						onecategoryData['elements'] = newElements;
					}
					categoryArr[j] = onecategoryData;
				}
				oneResult['years'] = categoryArr;
				resultArray[i] = oneResult;
			}
		} else {
			resultArray = categoryData;
		}
		var header = '<td width="80px" height="40px">科室</td>'+
			'<td width="40px" height="40px">总计</td>'+
			'<td width="40px" height="40px">年份</td>'+
			'<td width="40px" height="40px">年计</td>'
		if(category == "按季度") { //季度数据
			header += '<td class="quterYear">第一季度</td><td class="quterYear">第二季度</td>'+
				'<td class="quterYear">第三季度</td><td class="quterYear">第四季度</td>';
		} else if(category == "按月") { //月份数据
			header += '<td class="month">1</td><td class="month">2</td><td class="month">3</td>'+
				'<td class="month">4</td><td class="month">5</td><td class="month">6</td>'+
				'<td class="month">7</td><td class="month">8</td><td class="month">9</td>'+
				'<td class="month">10</td><td class="month">11</td><td class="month">12</td>';
		} else if(category == "按半年") { //半年
			header += '<td class="halfYear">上半年</td><td class="halfYear">下半年</td>'
		}else{
			header = '<td class="yearLoc" height="40px">科室</td>'+
				'<td class="yearOther" height="40px">总计</td>'+
				'<td class="yearOther" height="40px">年份</td>'+
				'<td class="yearOther" height="40px">年计</td>'
		}
		mui('#ExcelHead')[0].innerHTML = header
		mui('#scHeader')[0].innerHTML = header
		updateUIs(resultArray);
	}

	/*
	 * 更新表格内容
	 */
	function updateUIs(dataArr) {
		//console.log(JSON.stringify(dataArr));
		var ycTbody = document.getElementById('ycTbody');
		ycTbody.innerHTML = ''
		mui('.mui-scroll-wrapper').scroll().scrollTo(0, 0, 100)
		var totalHtml = "";
		var clasStr = ''
		for(var i = 0; i < dataArr.length; i++) {
			var oneData = dataArr[i];
			var data_years = oneData.years;
			var rowSpanNo = data_years.length;
			var rowSpanStr = ' rowspan="' + rowSpanNo + '"'
			var totalColorStr = ' style="color: red;"'
			//科室
			totalHtml += '<tr><td' + rowSpanStr + '>' + oneData.warddesc + '</td>'+
				'<td' + rowSpanStr + totalColorStr + '>' + oneData.total + '</td>';

			//年份/年计/半年-季度-月份
			for(var j = 0; j < data_years.length; j++) { //共有几年
				if (j > 0) {
					totalHtml += '<tr>'
				}
				var oneYearData = data_years[j];
				var backgroundStr = ' style="color: #24AF96;"'
				totalHtml += '<td class="web-font" ' + backgroundStr + '>' + oneYearData.year + '</td>'+
					'<td>' + oneYearData.partTotal + '</td>';
				//半年-季度-月份 elements
				var elementsArr = oneYearData.elements;
				if(category != "按年查询") {
					for(var k = 0; k < elementsArr.length; k++) {
						totalHtml += '<td>' + elementsArr[k] + '</td>';
					}
				}
				totalHtml += "</tr>";
			}
		}
		mui("#ycTbody")[0].innerHTML = totalHtml;
		var scroll = document.getElementById('scroll');
		scroll.style.top = 22 * 2 + 6 + 'px';
		plus.nativeUI.closeWaiting();
	};
	mui('.mui-scroll-wrapper').scroll();

	function selectionSetting() {
		var s = mui("input[name='check']");
		s.each(function(i) {
			$(this).click(function() {
				if(this.checked) {
					category = this.value;
					for(var i = 0; i < 4; i++) {
						var checkObj = document.getElementById("check" + (i + 1));
						if(this.id != "check" + (i + 1)) {
							checkObj.checked = false;
						}
					}
					updateHeader();
				} else { //取消选择 没有选择任何筛选条件  清除页面数据
					category = "";
					var ycTbody = document.getElementById('ycTbody');
					ycTbody.innerHTML = ''
				}
			});
		});
	}

	/*
	 * 选择开始时间和结束时间
	 * 选择结束时间后请求数据
	 */
	function selectDate(btn) {
		var dDate = new Date();
		var minDate = new Date();
		minDate.setFullYear(2007, 1, 1);
		var maxDate = new Date();
		maxDate.setFullYear(2099, 12, 31);
		plus.nativeUI.pickDate(function(e) {
			var d = e.date;
			var syear = d.getFullYear();
			var smonth = d.getMonth() + 1;
			var sday = d.getDate();
			var datestr = outDays(syear, smonth, sday);
			if(btn.id == "starttime") {
				var starttime = d.getTime();
				var endDate = getDateWithStr(endBtn.innerText);
				var endtime = endDate.getTime();
				btn.innerText = datestr;
				startTime = datestr;
				if(starttime > endtime) {
					mui.toast('请选择结束时间');
					selectDate(endBtn);
				} else {
					requestYCData();
				}
			} else if(btn.id == "endtime") {
				var startDate = getDateWithStr(startBtn.innerText);
				var starttime = startDate.getTime();
				var endtime = d.getTime();
				if(starttime > endtime) {
					mui.alert('结束时间不能晚于开始时间', '提示', '明白', selectDate(btn));
				} else {
					btn.innerHTML = datestr;
					endTime = datestr;
					requestYCData();
				}
			}
		}, function(e) {

		}, {
			title: "请选择日期",
			date: dDate,
			minDate: minDate,
			maxDate: maxDate
		});
	}
})();